<template>
	<view class="uni-flex uni-column w">
	<view class="uni-flex uni-column bd">
		<view class="flex-item header">
			todos
		</view>
		<view class="flex-item main">
			<uni-card>
			<view class="flex-item addBox">
				<uni-easyinput v-model="tmpText" prefixIcon="bottom" focus placeholder="输入待办..." @iconClick="markAll" @confirm="addTodo"></uni-easyinput>
			</view>
			<view class="flex-item content">
				<view v-for="(item, index) in this.todos" :key="item._id">
					<uni-easyinput :class="{completed:item.state?true:false}" :id="`todo-${item._id}`" :disabled="item.state?true:false" :prefixIcon="item.state?'checkbox':'circle'" suffixIcon="closeempty" v-model="item.title" placeholder="请输入内容" @iconClick="iconClick(item._id, index, $event)" @confirm="saveEdit(index, $event)">
						
					</uni-easyinput>
				</view>
			</view>
			<template v-slot:actions>
				<view class="uni-flex uni-row operate-bar">
					<view class="flex-item" style="width: 130rpx;">
						<text class="todo-count">未完成 {{leftCount}} 项</text>
					</view>
					<view class="flex-item filters">
						<view class="flex-item">
							<view class="filter-cond" :class="{selected: selectedType=='all'}" @click="getSpecialData('all')">All</view>
						</view>
						<view class="flex-item">
							<view class="filter-cond" :class="{selected: selectedType=='active'}"
										@click="getSpecialData('active')">Active</view>
						</view>
						<view class="flex-item">
							<view class="filter-cond" :class="{selected: selectedType=='completed'}"
										@click="getSpecialData('completed')">Completed</view>
						</view>
					</view>
					<view class="flex-item">
						<button class="clear-completed" @click="clearCompleted">隐藏已完成</button>
					</view>
				</view>
			</template>
			</uni-card>
		</view>
		<view class="flex-item ">
			<text class="footer">按下确认修改待办事项</text>
		</view>
	</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentEditing: null,
				todos: [],
				selectedType: 'All',
				tmpText:'',
				markState:0	// 批量标注成完成1或未完成0
			}
		},
		onLoad() {
			uni.request({
				url: 'http://127.0.0.1:3000/home',
				method: 'GET',
				data: {},
				success: res => {
					this.todos = res.data;
				},
				fail: () => {},
				complete: () => {}
			});
		},
		methods: {
			iconClick(id, index, event) {
				if(event==='suffix') { this.removeTodo(index) }
				else {
					this.changeState(index);
				}
			},
			addTodo(value) {
				// 1. 获取文本框中用户输入的数据
				// 2. 判断数据是否非空
				//    如果是空的，则什么都不做
				//    如果不是空的，则添加到数组中
				// 3. 添加到数据库中
				// 4. 清空文本框
				const todoText = value.trim()
				if (!todoText.length) {
					return
				}
				uni.request({
					url: 'http://127.0.0.1:3000/add-task',
					method: 'post',
					data: {
						'title': todoText
					},
					success: () => {
						uni.request({
							url: 'http://127.0.0.1:3000/home',
							method: 'GET',
							success: res=>{
								this.todos = res.data
								// 清空文本框
								this.tmpText = ''
							},
							fail: () => {},
							complete: () => {}
						})
					},
					fail: () => {
						console.log('服务器保存数据失败');
					},
					complete: () => {}
				});
				// axios.post('/add-task', {
				// 	'title': todoText
				// }).then(() => {
				// 	axios.get('/home')
				// 		.then(res => { this.todos = res.data })
				// 	// 清空文本框
				// 	event.target.value = ''
				// }).catch(() => {
				// 	console.log('服务器保存数据失败');
				// })
				// const lastTodo = this.todos[this.todos.length - 1]
				// const id = lastTodo ? lastTodo.id + 1 : 1

				// // 当数组发生变化，则绑定渲染该数组的视图也会得到更新
				// this.todos.push({
				//     id,
				//     title: todoText,
				//     completed: false
				// })
			},
			// 删除任务项
			removeTodo(delIndex, event) {
				uni.request({
					url: 'http://127.0.0.1:3000/task-del',
					method: 'GET',
					data: {
						id: this.todos[delIndex]._id
					},
					success: res => {
						uni.request({
							url: 'http://127.0.0.1:3000/home',
							method: 'GET',
							success: res=>{
								this.todos = res.data
							},
							fail: () => {},
							complete: () => {}
						})						
					},
					fail: () => {},
					complete: () => {}
				});
				// this.$axios({
				// 	method: 'get',
				//   url: "/task-del",
				//   params: {
				// 	  id: this.todos[delIndex]._id
				//   }
				// }).then(res => {
				// 	const data = res.data
				// 	console.log(data);
				// 	// if (data.success) {
				// 	// 	axios.get('http://127.0.0.1:3000/home')
				// 	// 		.then(res => { this.todos = res.data })
				// 	// }
				// });
				// axios.get('http://127.0.0.1:3000/task-del?id=' + this.todos[delIndex]._id).then(res => {
				// 	const data = res.data
				// 	if (data.success) {
				// 		axios.get('http://127.0.0.1:3000/home')
				// 			.then(res => { this.todos = res.data })
				// 	}
				// })
			},
			// 保存编辑项
			saveEdit(index, value) {
				var editText = value.trim()
				if (!editText.length) {
					// 将元素直接从数组中移除
					return this.todos.splice(index, 1)
				}
				uni.showLoading({
					title: '保存中'
				});
				
				// 2. 将数据设置到任务项中
				// item.title = editText
				uni.request({
					url: 'http://127.0.0.1:3000/task-modify',
					method: 'post',
					data: {
						id: this.todos[index]._id,
						title: editText
					},
					success: (res) => {
						const {data} = res
						if (data.success) {
							
							uni.request({
								url: 'http://127.0.0.1:3000/home',
								method: 'GET',
								success: res=>{
									this.todos = res.data
								},
								fail: () => {},
								complete: () => {}
							})	
						}
						uni.hideLoading();
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '保存数据失败',
							duration: 1000,
							icon: 'error'
						});
						console.log('服务器保存数据失败');
					},
					complete: () => {
						uni.hideLoading();
					}
				});
				// axios.post('/task-modify', {
				// 	id: this.todos[index]._id,
				// 	title: editText
				// }).then((res) => {
				// 	let data = res.data
				// 	if (data.success) {
				// 		axios.get('/home')
				// 			.then(res => { this.todos = res.data })
				// 	}
				// })

				// 3. 去除 editing 样式
				this.currentEditing = null
			},
			// 修改事件完成状态
			changeState(index) {
				this.todos[index].state = this.todos[index].state == 1 ? 0 : 1;
				uni.request({
					url: 'http://127.0.0.1:3000/change-state',
					method: 'post',
					data: {
						id: this.todos[index]._id
					},
					success: (res) => {
						const {data} = res
						if (data.success) {
							
							uni.request({
								url: 'http://127.0.0.1:3000/home',
								method: 'GET',
								success: res=>{
									this.todos = res.data
								},
								fail: () => {},
								complete: () => {}
							})	
						}
					},
					fail: () => {
						uni.showToast({
							title: '保存数据失败',
							duration: 1000,
							icon: 'error'
						});
						console.log('服务器保存数据失败');
					},
					complete: () => {
					}
				})
			},
			getSpecialData(url) {
				this.selectedType = url
				uni.request({
					url: 'http://127.0.0.1:3000/'+ url,
					method: 'get',
					data: {},
					success: (res) => {
						this.todos = res.data
					},
					fail: () => {
					},
					complete: () => {
					}
				})
			},
			clearCompleted() {
				uni.request({
					url: 'http://127.0.0.1:3000/clear-completed',
					method: 'get',
					data: {},
					success: (res) => {
						const {data} = res
						if (data.success) {
							
							uni.request({
								url: 'http://127.0.0.1:3000/home',
								method: 'GET',
								success: res=>{
									this.todos = res.data
								},
								fail: () => {},
								complete: () => {}
							})	
						}
					},
					fail: () => {
					},
					complete: () => {
					}
				})
			},
			markAll() {
				this.markState=this.markState?0:1
				uni.request({
					url: 'http://127.0.0.1:3000/mark-all',
					method: 'post',
					data: {
						state:this.markState
					},
					success: (res) => {
						const {data} = res
						if (data.success) {
							
							uni.request({
								url: 'http://127.0.0.1:3000/home',
								method: 'GET',
								success: res=>{
									this.todos = res.data
								},
								fail: () => {},
								complete: () => {}
							})	
						}
					},
					fail: () => {
						uni.showToast({
							title: '保存数据失败',
							duration: 1000,
							icon: 'error'
						});
						console.log('服务器保存数据失败');
					},
					complete: () => {
					}
				})
			}
		},
		computed: {
			toggleStat: {
				get() {
					console.log(2345)
					return this.todos.every(item => item.state)
				},
				set(val) {
					console.log(678)
					console.log(val)
					this.todos.forEach(todo => todo.state = val)
				}
			},
			leftCount: function () {
				return this.todos.filter(item => !item.state).length
			},

		},
		
	}
</script>

<style lang="scss">
	page {
		// 高度全屏
		height: 100%;
	}
	.w {
		width: 750rpx;
		height: 100%;
		background-color: rgb(234 234 234);
	}
	.bd {
		-webkit-flex: 1;
		flex: 1;
		margin: 0 20rpx;
		/* rgb(234 234 234); */
	}
	.header {
		font-size: 75rpx;
		font-weight: 100rpx;
		text-align: center;
		color: rgba(175, 47, 47, 0.15);
	}
	.new-todo {
		padding-left: 35rpx;
		text-align: start;
	}
	.new-todo::before {
		content:'>';
		font-size: 22rpx;
	    color: rgb(230, 230, 230);
	}
	.toggle-all {
		opacity: 0;
	}
	.toggle-all + label {
	    width: 60rpx;
	    height: 34rpx;
	    font-size: 0;
	    position: absolute;
	    top: -52rpx;
	    left: -13rpx;
	    -webkit-transform: rotate(90deg);
	    transform: rotate(90deg);
	}
	
	.toggle-all + label::before {
	    content: "❯";
	    font-size: 22rpx;
	    color: rgb(230, 230, 230);
	    padding: 10rpx 27rpx;
	}
	.operate-bar {
		width: 100%;
		height: 50rpx;
		-webkit-justify-content: space-between;
		justify-content: space-between;
		-webkit-align-items:center;
		align-items:center;
		color: #777;
	}
	.todo-count {
		white-space:nowrap;
	}
	.filters {
		display: flex;
		height: 40rpx;
		-webkit-flex: 1;
		flex: 1;
		-webkit-justify-content: center;
		justify-content: center;
		-webkit-align-items:center;
		align-items:center;
		.flex-item {
			.filter-cond {
				box-sizing: border-box;
				padding: 3rpx 7rpx;
				border: 1px solid transparent;
				border-radius: 3px;
			}
			.selected {
				border-color: rgba(175, 47, 47, 0.2);
			}
		}
		
	}
	.clear-completed {
		box-sizing: border-box;
		margin: 0rpx;
		padding: 0rpx;
		width: 150rpx;
		height: 35rpx;
		line-height: 35rpx;
		white-space:nowrap;
		font-size: 12rpx;
		color: inherit;
	}
	.footer {
		width: 750rpx;
		display: inline-block;
		color: #bfbfbf;
		font-size: 25rpx;
		text-shadow: 0 1rpx 0 rgba(255, 255, 255, 0.5);
		text-align: center;
	}
	.uni-easyinput.completed {
		::v-deep input.uni-input-input {
			text-decoration: line-through;
		}
	}
</style>
